import { asyncRouterMap, constantRouterMap } from '@/router'

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('@/router/modules/import-' + process.env.NODE_ENV)
console.log(_import)

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}


/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {...route}
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ dispatch, commit }, data) {
      const { menuList } = data
      function fnAddDynamicMenuRoutes(menuList, routers) {
        for (var i = 0; i < menuList.length; i++) {
          var route = {
            path: menuList[i].path,
            component: _import(menuList[i].component),
            name: menuList[i].name,
            meta: menuList[i].meta
          }
          if (menuList[i].list && menuList[i].list.length >= 1) {
            route.children = [] // 当前这一层所有
            routers.push(route)
            fnAddDynamicMenuRoutes(menuList[i].list, route.children)
          } else {
            routers.push(route)
          }
        }
        commit('SET_ROUTERS', routers)
      }
      if (menuList) {
        fnAddDynamicMenuRoutes(menuList, [])
      }
      //   // url以http[s]://开头, 通过iframe展示
      //   // if (isURL(menuList[i].url)) {
      //   //   route['path'] = `i-${menuList[i].menuId}`
      //   //   route['name'] = `i-${menuList[i].menuId}`
      //   //   route['meta']['iframeUrl'] = menuList[i].url
      //   // } else {
      //   //   try {
      //   //     route['component'] = _import(`modules/${menuList[i].url}`) || null
      //   //   } catch (e) {}
      //   // }
      //   // routes.push(route)



    }
  }
}

export default permission
